package com.atbeijing.kafka.produce;

import org.apache.kafka.clients.producer.Callback;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;

import java.io.IOException;
import java.util.Properties;
import java.util.concurrent.Future;

public class ProducerCallBack {
    public static void main(String[] args) {
        Properties conf = new Properties();
        try {
            //通过当前类获取类加载器,以流的方式加载配置文件
            conf.load(ProducerCallBack.class.getClassLoader().getResourceAsStream("producer.properties"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        //泛型为消息的kv类型
        KafkaProducer<String, String> produce = new KafkaProducer<String, String>(conf);
        for (int i = 0; i < 10; i++) {
            //发送消息,有回调函数
            Future<RecordMetadata> send = produce.send(new ProducerRecord<String, String>("first", "01", "01hello"),
                    //回调函数,循环发送不会等待回执函数就继续往下执行
                    new Callback() {
                        public void onCompletion(RecordMetadata recordMetadata, Exception e) {
                            if (recordMetadata != null) {
                                System.out.println("成功了");
                            } else {
                                System.out.println("失败了");
                            }
                        }
                    }
            );
            System.out.println("第" + i + "条消息已发送");
        }

        //关闭资源
        produce.close();
    }
}
